<?php
/**
 * 群发短信接口
 * @author 陈凯强
 */

namespace App\Http\Controllers\Api;

use App\Http\Services\Oss;
use App\Libs\PHPExcel\PHPExcel\PHPExcel_IOFactory;
use App\Model\SmsAll;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class SmsController extends BaseController
{
    protected $service;//实例化服务
    protected $oss;//实例化服务

    public function __construct(Request $request)
    {
        $this->service = new SmsAll();
        $this->oss = new Oss();
        parent::__construct($request);
    }

    /**
     * 新增群发
     */
    public function addSms(Request $request)
    {
        //接收参数
        $params = $request->all();
        if (empty($params['phone']) && empty($params['fileurl'])) {
            return $this->toJson(self::ERROR, [], '缺少手机号参数');
        }
        if (empty($params['content'])) {
            return $this->toJson(self::ERROR, [], '发送文案必填');
        }
        $time = time();
        $params['sendtime'] = empty($params['sendtime']) ? $time : strtotime(date("Y-m-d H:i",strtotime($params['sendtime']))); //发送时间
        $params['note'] = empty($params['note']) ? '' : $params['note']; //备注
        $params['fileurl'] = empty($params['fileurl']) ? '' : $params['fileurl']; //文件url
        $finalstr = '';
        if (!empty($params['fileurl'])) {
            $fileurl = build_image( '/'.$request['fileurl']);
            //下载文件
            $filepath = storage_path().'/'.'phone.xls';
            file_put_contents($filepath, file_get_contents($fileurl));
            //读取Excel信息
            $array = excel_to_array($filepath, 1, '', 1);
            if (!empty($array['content'])) {
                foreach ($array['content'] as $k => $v) {
                        $v=array_filter($v);
                        $phoneArr[] = $v;      
                }
                $phoneArr = array_reduce($phoneArr,'array_merge',[]);
                $finalstr = implode(',', $phoneArr);
            }
        }
        $params['finalstr'] = !empty($finalstr) ? $finalstr : '';
        //实例化table
        $status = $this->service->addLists($params);
        //立即发送条件
        if ($params['sendtime'] == $time &&  $status['code']==0)
        {
            $this->mustSend($params,$finalstr,$status);
        }
        if ($status['code'] != 0) {
            return $this->toJson(self::ERROR, [], '新增失败');
        }
        return $this->toJson(self::SUCCESS, [], 'ok');
    }

    /**
     * 群发短信列表
     */
    public function smsList(Request $request)
    {
        $page = $request->get('page', 1);
        $limit = $request->get('limit', 10);
        //实例化table
        $smslits = $this->service->getSmsLit($page, $limit);
        return $this->toJson(self::SUCCESS, $smslits, 'ok');
    }

    /**
     * 更改短信
     */
    public function smsChange(Request $request)
    {
        $params = $request->all();
        if (empty($params['smsid'])) {
            return $this->toJson(self::ERROR, [], '缺少id');
        }
        if (empty($params['phone'])) {
            return $this->toJson(self::ERROR, [], '缺少参数');
        }
        if (empty($params['content'])) {
            return $this->toJson(self::ERROR, [], '发送文案必填');
        }
        $time = time();
        $params['sendtime'] = empty($params['sendtime']) ? $time : strtotime(date("Y-m-d H:i",strtotime($params['sendtime'])));
        $params['note'] = empty($params['note']) ? '' : $params['note'];
        $params['fileurl'] = empty($params['fileurl']) ? '' : $params['fileurl'];
        $finalstr = '';
        if (!empty($request['fileurl'])) {
            $fileurl = build_image( '/'.$request['fileurl']);
            $filepath = storage_path().'/'.'phone.xls';
            file_put_contents($filepath, file_get_contents($fileurl));
            //读取Excel信息
            $array = excel_to_array($filepath, 1, '', 1);
            if (!empty($array['content'])) {
                foreach ($array['content'] as $k => $v) {
                    $v=array_filter($v);
                    $phoneArr[]=$v;
                    $phoneArr = array_reduce($phoneArr,'array_merge',[]);
                }
                $finalstr = implode(',', $phoneArr);
            }
        }
        $params['finalstr'] = !empty($finalstr) ? $finalstr : '';
        //实例化table
        $status = $this->service->smsChange($params);
        //立即发送条件
        if ($params['sendtime'] == $time &&  $status['code']==0)
        {
            $status['data'] = $params['smsid'];
            $this->mustSend($params,$finalstr,$status);
        }
        if ($status['code'] != 0) {
            return $this->toJson(self::ERROR, [], '更改失败');
        }
        return $this->toJson(self::SUCCESS, [], 'ok');
    }

    /**
     * 更改内容前置接口
     */
    public function getSmsInfo(Request $request)
    {
        //获取单条群发短信信息
        $smsid = $request->post('smsid');//短信id
        $info = $this->service->getOne($smsid);
        if (!empty($info)) {
            $info['create_time'] = date('Y-m-d H:i', $info['create_time']);
            $info['sendtime'] = date('Y-m-d H:i', $info['sendtime']);
        }
        return $this->toJson(self::SUCCESS, $info, 'ok');
    }

    /**
     * 撤回状态
     */
    public function statusChange(Request $request)
    {
        $params = $request->all(); //接收参数
        if (empty($params['smsid'])) {
            return $this->toJson(self::ERROR, [], '缺少id');
        }
        //实例化table
        $status = $this->service->smsStatusChange($params);
        if ($status['code'] != 0) {
            return $this->toJson(self::ERROR, [], '更改失败');
        }
        return $this->toJson(self::SUCCESS, [], 'ok');
    }

    /**
     * 获取详情
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function GetSmsAllDetial(Request $request)
    {
        $smsid = $request->get('smsid');
        $page = $request->get('page', 1);
        $limit = $request->get('limit', 10);
        //查询数据
        $res = $this->service->getSmsLog($smsid,$page,$limit);
        if (!empty($res['data'])) {
            $res['failcount'] = 0; //失败数
            $res['successcount'] = 0; //成功发送数
            foreach ($res['data'] as $k => $v) {
                if ($v['status'] == 'FAILURE') {
                    $res['data'][$k]['status'] = '失败';
                    $res['failcount'] += 1;
                } else if($v['status'] == 'DELIVRD'){
                    $res['data'][$k]['status'] = '成功';
                    $res['successcount'] += 1;
                }else if($v['status'] == 'UT:0009'){
                    $res['data'][$k]['status'] = '地区屏蔽';
                    $res['failcount'] += 1;
                }
            }
        }
        return $this->toJson(self::SUCCESS, $res, 'ok');
    }

    /**
     * 下载对应群发短信中失败的用户手机号
     *
     */
    public function download(Request $request)
    {
        $smsid = $request->get('smsid'); //短信id
        if (empty($smsid))
        {
            return $this->toJson(self::ERROR, [], '缺少id');
        }
        //查询对应失败的手机数据
        $fialres = $this->service->downlowData($smsid);
        //生成文件下载
        $fileData = '手机号' . "\n";
        foreach ($fialres as $value) {
            $temp = $value['phone'] ;
            $fileData .= $temp. "\n";
        }
        // 将一个字符串写入文件
        $filename = $smsid.'手机名单'.'.csv';
        Storage::put($filename, $fileData);
        //上传oss
        $upload_config =  curl_request(config('kkaudio.kkaudio_api') . "/inner/system/put_file_url", ['type' => 24, 'exts' => 'csv', 'noase' => 1], $contentType = 'urlencoded', $httpMethod = 'GET');

        $uri = $upload_config['data'][0]['uri'];
        $formatUri = ltrim($uri, '/');
        $localFilePath = storage_path('app'.'/'.$filename);
        $ossRes = $this->oss->uploadFile($formatUri, $localFilePath);
        if (!$ossRes) {
            return $this->toJson(self::ERROR, '上传文件过程中发生错误');
        }
        $url = $upload_config['data'][0]['url'];
        return $this->toJson(self::SUCCESS, $url, 'ok');
    }

    /**
     * 立即发送短息
     */
    public function mustSend($params,$finalstr=null,$status=[])
    {
        return $this->service->fastSend($params,$finalstr,$status);
    }

}
